package com.bobamrz.frontend;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.InvalidParameterException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bobamrz.service.DocumentService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class DocumentFormJsonServlet extends SuperServlet {
	
	protected void processGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		if (id == null || id.equals("")) {
			throw new InvalidParameterException();
		} 
		
		List<Map<String, Object>> documentData = null;
		DocumentService ds = new DocumentService();
		if (id.equals("new")) {
			String docType = request.getParameter("doc_type");
			if(docType == null || docType.equals("")) {
				throw new InvalidParameterException();
			} 
			documentData = ds.getNewDocumentData(docType);	
		} else {
			documentData = ds.getDocumentData(Long.parseLong(id));
		}
		
		Gson gson = new GsonBuilder().serializeNulls().create();
		String jsonData = gson.toJson(documentData);

		PrintWriter writer = null;
		try {
			writer = new PrintWriter(response.getOutputStream());
			writer.write(jsonData);
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}
}
